import { defineStore } from "pinia";
import { ref } from "vue";
import {
  WaveCfg,
  WaveChartAPI,
  type WaveRecordPayload,
  type WaveRecordResponse,
  type WaveBackupInfoItem,
  type WaveBackupInfoResponse,
  type WaveBackupActionResponse,
} from "@/api/hmi/wave-chart.api";

/**
 * 波形图数据 Store
 */
export const useWaveChartStore = defineStore("wave-chart", () => {
  // 波形配置
  const waveCfg = ref<WaveCfg | null>(null);
  // 波形数据
  const waveData = ref<any>(null);

  // 加载状态
  const loading = ref<boolean>(false);

  // 错误信息
  const error = ref<string | null>(null);

  /**
   * 获取波形数据
   * @param cpu CPU编号
   * @param faultFileName 故障文件名
   */
  const fetchWaveData = async (cpu: number, faultFileName: string) => {
    try {
      loading.value = true;
      error.value = null;

      const cfgRes = await WaveChartAPI.fetchWaveData(cpu, 0, faultFileName);
      // waveCfg.value = cfg_data;

      const datRes = await WaveChartAPI.fetchWaveData(cpu, 1, faultFileName);
      // waveData.value = dat_data;
      console.log("波形数据获取成功", { cfgRes, datRes });
      return { cfgRes, datRes };
    } catch (err: any) {
      error.value = err.message || "获取波形数据失败";
      throw err;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 清除波形数据
   */
  const clearWaveData = () => {
    waveData.value = null;
    error.value = null;
  };

  /**
   * 手动录波
   * @param cpu CPU 编号
   * @param payload 录波参数（数组形式）
   * @returns Promise<WaveRecordResponse | null>
   */
  const manualWaveRecord = (
    cpu: number,
    payload: WaveRecordPayload
  ): Promise<WaveRecordResponse | null> => {
    return new Promise((resolve) => {
      WaveChartAPI.manualWaveRecord(cpu, payload)
        .then((res: WaveRecordResponse) => {
          if (res && res.status === "Success") {
            resolve(res);
          } else {
            resolve(null);
          }
        })
        .catch(() => {
          resolve(null);
        });
    });
  };

  /**
   * 查询录波备份信息
   * @param cpu CPU 编号
   * @returns Promise<WaveBackupInfoItem | null>
   */
  const queryWaveBackupInfo = (cpu: number): Promise<WaveBackupInfoItem | null> => {
    return new Promise((resolve) => {
      WaveChartAPI.fetchWaveBackupInfo(cpu)
        .then((res: WaveBackupInfoResponse) => {
          if (Array.isArray(res) && res.length > 0) {
            resolve(res[0]);
          } else {
            resolve(null);
          }
        })
        .catch(() => resolve(null));
    });
  };

  /**
   * 触发录波备份
   * @param cpu CPU 编号
   * @returns Promise<WaveBackupActionResponse | null>
   */
  const triggerWaveBackup = (cpu: number): Promise<WaveBackupActionResponse | null> => {
    return new Promise((resolve) => {
      WaveChartAPI.triggerWaveBackup(cpu)
        .then((res: WaveBackupActionResponse) => {
          if (res && typeof res.success === "number") {
            resolve(res);
          } else {
            resolve(null);
          }
        })
        .catch(() => resolve(null));
    });
  };

  return {
    waveCfg,
    waveData,
    loading,
    error,
    fetchWaveData,
    clearWaveData,
    manualWaveRecord,
    queryWaveBackupInfo,
    triggerWaveBackup,
  };
});
